<script setup>
import { Modal } from 'ant-design-vue'
import { CheckCircleOutlined, ColumnHeightOutlined, DeleteOutlined, DoubleRightOutlined, DownOutlined, EditOutlined, InfoCircleOutlined, KeyOutlined, LockOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UndoOutlined, UpOutlined } from '@ant-design/icons-vue'
import { addBankCard, addHospital, getHospitalDetail, getHospitalList, setDefaultCard, unbindCard, updateHospital } from '~@/api/hospital/index'
import { getMerchantList } from '~@/api/card/index'

defineOptions({
  name: 'Hospital',
})
// 新增医院
const hosForm = ref()
const bankForm = ref()
const userTitle = shallowRef('')
const hosOpen = ref(false)
const cardOpen = ref(false)
const bankOpen = ref(false)
const giftOpen = ref(false)
const giftLoading = ref(false)
const allocateLoading = ref(false)
const editInfo = reactive({
  roleId: null,
})
const totalInfo = shallowRef({
  batchSum: 0,
  totalSum: 0,
  storageSum: 0,
})

const confirmLoading = ref(false) // 确认加载中

const bankLoading = ref(false)

const rules = computed(() => {
  return {
    hospitalName: [
      { required: true, message: '请填写医院名称', trigger: 'change' },
    ],
    hosCertType: [
      { required: true, message: '请选择银行名称', trigger: 'change' },
    ],
    hosCertNo: [
      { required: true, message: '请填写医院证件号', trigger: 'change' },
    ],
    legalName: [
      { required: true, message: '请填写法人姓名', trigger: 'change' },
    ],
    legalCertNo: [
      { required: true, message: '请填写法人证件号', trigger: 'change' },
    ],
    hosRealaddr: [
      { required: true, message: '请填写营业执照范围', trigger: 'change' },
    ],
    hosCertExpireDate: [
      { required: true, message: '请选择医院证件过期时间', trigger: 'change' },
    ],
    legalCertExpireDate: [
      { required: true, message: '请选择法人证件过期时间', trigger: 'change' },
    ],
  }
})
const bankRules = computed(() => {
  return {
    bankCode: [
      { required: true, message: '请选择银行名称', trigger: 'change' },
    ],
    cardNo: [
      { required: true, message: '请填写银行卡号', trigger: 'change' },
    ],
    unBankNo: [
      { required: true, message: '请填写开户银行联行号', trigger: 'change' },
    ],
  }
})

const options = ref([])
const saleOptions = ref([])
const hospitalOptions = ref([
  { configKey: '02', configValue: '组织机构代码' },
  { configKey: '03', configValue: '统一社会信用代码' },
  { configKey: '04', configValue: '民办非企业登记证书' },
  { configKey: '05', configValue: '社会团体法人登记证书' },
  { configKey: '06', configValue: '事业单位法人登记证' },
  { configKey: '07', configValue: '营业执照号码' },
  { configKey: '08', configValue: '其他单位证件' },
])
const bankOptions = ref([
  { configKey: 'ICBC', configValue: '中国工商银行' },
  { configKey: 'CITIC', configValue: '中信银行' },
  { configKey: 'ABC', configValue: '中国农业银行' },
  { configKey: 'CCB', configValue: '中国建设银行' },
  { configKey: 'BCM', configValue: '交通银行' },
  { configKey: 'CMBC', configValue: '中国民生银行' },
  { configKey: 'BOC', configValue: '中国银行' },
])

const formState = reactive({
  id: null,
  hospitalName: '',
  hosCertType: '',
  hosCertNo: '',
  legalName: '',
  legalCertNo: '',
  legalCertType: '01',
  hosRealaddr: '',
  hosCertExpireDate: '',
  legalCertExpireDate: '',
})
const bankState = reactive({
  id: null,
  bankCode: '',
  cardNo: '',
  unBankNo: '',
})

const salesState = reactive({
  cardNo: '',
  status: '',

})
const giftInfo = reactive({
  remarks: '',
})

const message = useMessage()
const selectedRowKeys = shallowRef([])
const giftData = shallowRef([])
const giftDetailData = shallowRef([])

const columns = shallowRef([
  {
    title: '医院名称',
    dataIndex: 'hospitalName',
    width: 250,
    ellipsis: true,
  },

  {
    title: '医院证件类型',
    dataIndex: 'hosCertType',
    width: 180,
    customRender: ({ text }) => {
      switch (text) {
        case '02':
          return '组织机构代码'
        case '03':
          return '统一社会信用代码'
        case '04':
          return '民办非企业登记证书'
        case '05':
          return '社会团体法人登记证书'
        case '06':
          return '事业单位法人登记证'
        case '07':
          return '营业执照号码'
        default:
          return '其他单位证件'
      }
    },
  },
  {
    title: '医院证件号',
    dataIndex: 'hosCertNo',
    width: 200,
  },
  {
    title: '法人姓名',
    dataIndex: 'legalName',
    width: 150,

  },
  {
    title: '法人证件类型',
    dataIndex: 'legalCertType',
    width: 150,
    customRender: ({ text }) => {
      switch (text) {
        case '01':
          return '身份证'
      }
    },
  },
  {
    title: '法人证件号',
    dataIndex: 'legalCertNo',
    width: 200,

  },
  {
    title: '营业执照范围',
    dataIndex: 'hosRealaddr',
    width: 200,
    ellipsis: true,

  },
  // {
  //   title: '创建日期',
  //   dataIndex: 'createTime',
  //   width: 200,

  // },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: '180px',

  },
])
const giftColumns = shallowRef([
  {
    title: '卡号',
    dataIndex: 'cardNo',
    width: 300,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 300,
    customRender: ({ text }) => {
      switch (text) {
        case 'DEFRAY':
          return '支付'
        case 'REFUND':
          return '退费'
        case 'RECHARGE':
          return '充值'
        default:
          return '提现'
      }
    },
  },
  {
    title: '登记时间',
    dataIndex: 'activeTime',
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },
  },

])
const bindColumns = shallowRef([
  {
    title: '银行名称',
    dataIndex: 'bankName',
  },
  {
    title: '银行卡号',
    dataIndex: 'cardNo',
  },
  {
    title: '开户银行联行号',
    dataIndex: 'unBankNo',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: '180px',

  },

])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const totalDetailNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const cardList = shallowRef([])// 已绑卡列表
const formModel = reactive({
  roleName: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)

const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
onMounted(() => {
  init()
})

// 查询医院注册列表
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getHospitalList({
      param: { ...formModel },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
function handleChange(value) {
  console.log(`selected ${value}`)
}
function handleBlur() {
  console.log('blur')
}
function handleFocus() {
  console.log('focus')
}
function filterOption(input, option) {
  return option.label.toLowerCase().includes(input.toLowerCase())
}
// 搜索
async function onSearch() {
  pagination.current = 1
  await init()
}
// 导出
async function exportExcel(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await exportCard(record.id)
    if (data.url) {
      window.location.href = data.url
    }
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

// 医院信息变更
async function handleView(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const params = {
      id: record.id,
    }
    const { data } = await getHospitalDetail(params)
    loading.value = false
    userTitle.value = '信息变更'
    hosOpen.value = true
    formState.id = data.id
    formState.hospitalName = data.hospitalName
    formState.hosCertType = data.hosCertType
    formState.hosCertNo = data.hosCertNo
    formState.legalName = data.legalName
    formState.legalCertType = data.legalCertType
    formState.legalCertNo = data.legalCertNo
    formState.hosRealaddr = data.hosRealaddr
    formState.hosCertExpireDate = data.hosCertExpireDate
    formState.legalCertExpireDate = data.legalCertExpireDate
  }
  catch (e) {
    loading.value = false
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 打卡卡管理界面
function handleCard(record) {
  formState.id = record.id
  formState.hospitalName = record.hospitalName
  getDetail('card')
}

// 查询医院详情
async function getDetail(type) {
  if (loading.value)
    return
  loading.value = true
  try {
    const params = {
      id: formState.id,
    }
    const { data } = await getHospitalDetail(params)
    cardList.value = data.cardInfoList
    if (type) {
      loading.value = false
      cardOpen.value = true
    }
  }
  catch (e) {
    loading.value = false
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 添加银行卡
function addBank() {
  if (bankForm.value) {
    bankForm.value.resetFields()
  }
  resetBank()
  bankOpen.value = true
}
// 取消绑卡 handleAddCancel
async function handleAddCancel() {
  if (bankForm.value) {
    bankForm.value.resetFields()
  }
  resetBank()
}
// 确认绑卡
async function handleAddOk() {
  bankLoading.value = true
  try {
    await bankForm.value.validate()
    bankState.id = formState.id
    const params = {
      id: bankState.id,
      cardInfoVo: bankState,
    }

    const { data } = await addBankCard(params)
    if (data.code === 'SUCCESS') {
      bankLoading.value = false
      bankOpen.value = false
      message.success('添加成功')
      getDetail()
    }
    else {
      bankLoading.value = false
    }
  }
  catch (error) {
    bankLoading.value = false
    // message.error('请检查表单填写是否正确')
  }
}
// 解绑银行卡
async function handleUnbind(record) {
  Modal.confirm({
    title: '确认操作',
    centered: true,
    content: `确认解绑此银行卡？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = unbindCard({ id: record.id, userId: record.userId })
          .then((res) => {
            if (res.code === 'SUCCESS') {
              setTimeout(() => {
                resolve()
                getDetail()
                message.success('解绑成功')
              }, 500)
            }
            else {
              message.error('解绑失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            getDetail()
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 设置默认卡
async function handleDefault(record) {
  Modal.confirm({
    title: '确认操作',
    centered: true,
    content: `确定将${record.bankName}卡设置为默认卡？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = setDefaultCard({ id: record.id })
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              setTimeout(() => {
                resolve()
                getDetail()
                message.success('设置成功')
              }, 500)
            }
            else {
              message.error('设置失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 医院注册
function addRoleModal() {
  if (hosForm.value) {
    hosForm.value.resetFields()
  }
  resetHos()
  userTitle.value = '医院注册'
  hosOpen.value = true
}
// 确认注册医院
async function handleOk() {
  confirmLoading.value = true
  try {
    await hosForm.value.validate()
    if (formState.id) {
      const { data } = await updateHospital(formState)
      if (data.code === 'SUCCESS') {
        confirmLoading.value = false
        hosOpen.value = false
        message.success('保存成功')
        init()
      }
      else {
        confirmLoading.value = false
      }
    }
    else {
      const { data } = await addHospital(formState)
      if (data.code === 'SUCCESS') {
        confirmLoading.value = false
        hosOpen.value = false
        message.success('注册成功')
        init()
      }
      else {
        confirmLoading.value = false
      }
    }
  }
  catch (error) {
    confirmLoading.value = false
    // message.error('请检查表单填写是否正确')
  }
}

// 关闭弹窗
function handleCancel() {
  if (hosForm.value) {
    hosForm.value.resetFields()
  }
  resetHos()
  hosOpen.value = false
}
// 重置医院注册信息
function resetHos() {
  formState.id = void 0
  formState.hospitalName = void 0
  formState.hosCertType = void 0
  formState.hosCertNo = void 0
  formState.legalName = void 0
  formState.legalCertNo = void 0
  formState.legalCertType = '01'
  formState.hosRealaddr = void 0
  formState.hosCertExpireDate = void 0
  formState.legalCertExpireDate = void 0
}

// 重置银行卡信息
function resetBank() {
  bankState.bankCode = void 0
  bankState.cardNo = void 0
  bankState.unBankNo = void 0
}

function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
watch(
)
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :model="formModel" layout="inline">
        <a-form-item name label="医院名称">
          <a-input v-model:value="formModel.hospitalName" placeholder="医院名称" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-space flex justify-end w-full>
            <a-button type="primary" @click="onSearch">
              <SearchOutlined />查询
            </a-button>
            <a-button type="primary" class="ml-2" ghost @click="addRoleModal">
              <PlusOutlined />医院注册
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'faceAmount'">
            <span>{{ Number(record.faceAmount).toFixed(2) }}</span>
          </template>

          <template v-else-if="column.dataIndex === 'action'">
            <div class="action flex flex-center">
              <a @click="handleView(record)">信息变更</a>
              <span class="middle-line">|</span>
              <a @click="handleCard(record)">卡管理</a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 医院注册 -->
    <a-modal v-model:open="hosOpen" :mask-closable="false" width="900px" :title="userTitle" :body-style="{ paddingTop: '25px', paddingBottom: '0px' }" ok-text="确定" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <a-form
        ref="hosForm"
        :model="formState"
        :rules="rules"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="hospitalName" label="医院名称">
              <a-input v-model:value="formState.hospitalName" placeholder="医院名称" allow-clear />
            </a-form-item>
            <a-form-item name="hosCertType" label="证件类型">
              <a-select v-model:value="formState.hosCertType" placeholder="请选择证件类型" allow-clear>
                <a-select-option v-for="item in hospitalOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item name="hosCertNo" label="证件号码">
              <a-input v-model:value="formState.hosCertNo" placeholder="证件号码" allow-clear />
            </a-form-item>
            <a-form-item name="hosCertExpireDate" label="医院证件过期时间">
              <a-date-picker
                v-model:value="formState.hosCertExpireDate" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 100%;" placeholder="请选择日期"
              />
            </a-form-item>
            <a-form-item name="legalName" label="法人姓名">
              <a-input v-model:value="formState.legalName" placeholder="法人姓名" allow-clear />
            </a-form-item>
            <a-form-item name="legalCertType" label="法人证件类型">
              <a-radio-group v-model:value="formState.legalCertType">
                <a-radio value="01">
                  身份证
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item name="legalCertNo" label="法人证件号">
              <a-input v-model:value="formState.legalCertNo" placeholder="法人证件号" allow-clear />
            </a-form-item>
            <a-form-item name="legalCertExpireDate" label="法人证件过期时间">
              <a-date-picker
                v-model:value="formState.legalCertExpireDate" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 100%;" placeholder="请选择日期"
              />
            </a-form-item>
            <a-form-item name="hosRealaddr" label="营业执照范围">
              <a-textarea v-model:value="formState.hosRealaddr" placeholder="营业执照范围" :rows="3" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <!-- 卡管理 -->
    <a-modal v-model:open="cardOpen" :mask-closable="false" width="1000px" :footer="false" :title="formState.hospitalName" :body-style="{ height: '500px', paddingTop: '15px', paddingBottom: '0px' }" ok-text="确定" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
      <a-card title="已绑银行卡列表">
        <template #extra>
          <a-space flex justify-end w-full>
            <a-button type="primary" class="ml-2" ghost @click="addBank">
              <PlusOutlined />添加银行卡
            </a-button>
          </a-space>
        </template>
        <a-table bordered :loading="loading" :columns="bindColumns" :data-source="cardList" :pagination="false">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'bankName'">
              <span>{{ record.bankName }} </span>
              <a-tag
                v-if="record.default === true"
                class="ml-2"
                :color="record.default === true ? 'geekblue' : 'volcano'"
              >
                默认
              </a-tag>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <div class="action flex flex-center">
                <a @click="handleUnbind(record)">解绑</a>
                <span class="middle-line">|</span>
                <a @click="handleDefault(record)">设置默认卡</a>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-modal>
    <!-- 绑定卡 -->
    <a-modal v-model:open="bankOpen" :mask-closable="false" width="620px" style="top: 220px" :body-style="{ paddingTop: '40px', paddingBottom: '30px' }" title="添加银行卡" :confirm-loading="bankLoading" @ok="handleAddOk" @cancel="handleAddCancel">
      <a-form
        ref="bankForm"
        :model="bankState"
        :rules="bankRules"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="bankCode" label="银行名称">
              <a-select v-model:value="bankState.bankCode" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in bankOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item name="cardNo" label="银行卡号">
              <a-input v-model:value="bankState.cardNo" placeholder="银行卡号" allow-clear />
            </a-form-item>
            <a-form-item name="unBankNo" label="开户银行联行号">
              <a-input v-model:value="bankState.unBankNo" placeholder="开户银行联行号" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </page-container>
</template>

    <style lang="less" scoped>
      :deep(.ant-btn){
        padding: 4px 8px;
      }
      .ant-divider-horizontal{
        margin: 15px 0;
      }
      .line{
        color:#1677ff;
      }
      .userTitle{
        color:gray;
        width: 100%;
        padding:5px 0;
        border-bottom:1px solid #f1eded;
        margin-bottom: 20px;
      }
      .red{
        color:red;
        /* color:#ff4d4f; */
      }
      .card-title{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        flex: auto;
        color: rgba(0, 0, 0, 0.88);
        font-weight: 600;
        font-size: 16px;
        line-height: 1.5;
      }
    @media screen and (max-width: 1200px) and (min-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        margin-left: -44px;
        .statItem {
          padding: 0 16px;
        }
      }
    }

    @media screen and (max-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        float: none;
        margin-right: 0;
        .statItem {
          padding: 0 16px;
          text-align: left;
          &::after {
            display: none;
          }
        }
      }
    }

    @media screen and (max-width: 768px) {
      .extraContent {
        margin-left: -16px;
      }
      .projectList {
        .projectGrid {
          width: 50%;
        }
      }
    }

    @media screen and (max-width: 576px) {
      .pageHeaderContent {
        display: block;
        .content {
          margin-left: 0;
        }
      }
      .extraContent {
        .statItem {
          float: none;
        }
      }
    }

    @media screen and (max-width: 480px) {
      .projectList {
        .projectGrid {
          width: 100%;
        }
      }
    }
    </style>

    <style>
      [class^="ant-checkbox-group"] [class*=" ant-checkbox-group"]{
        margin:10px !important;
        width:190px !important;
      }
</style>
